package com.example.listview

import android.app.Activity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView.ViewHolder

/**
 * 水果列表适配器
 * @param activity 宿主Activity
 * @param resourceId item布局id
 * @param data FruitItem列表
 */
class FruitAdapter(activity: Activity, val resourceId: Int, data: List<FruitItem>) : ArrayAdapter<FruitItem>(activity, resourceId, data) {
    /**
     * Kotlin中使用inner class关键字来定义内部类
     * 通过对ImageView和TextView的控件实例进行缓存
     * 避免每次在getView()方法中都调用View的findViewById()方法重新去获取一次控件的实例
     */
    inner class  ViewHolder(val fruitImage: ImageView, val fruitName: TextView)
    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        val view: View
        val viewHolder: ViewHolder
        // convertView参数用于将之前加载好的布局进行缓存，以便之后进行重用
        if (convertView == null) {
            view = LayoutInflater.from(context).inflate(resourceId, parent, false)
            val fruitImage: ImageView = view.findViewById(R.id.fruitImage)
            val fruitName: TextView = view.findViewById(R.id.fruitName)
            viewHolder = ViewHolder(fruitImage, fruitName)
            view.tag = viewHolder
        } else {
            view = convertView
            viewHolder = view.tag as ViewHolder

        }
        val fruit = getItem(position) // 获取当前项的Fruit实例
        if (fruit != null) {
            viewHolder.fruitImage.setImageResource(fruit.imageId)
            viewHolder.fruitName.text = fruit.name
        }
        return view
    }
}